<template>
  <el-dialog v-model="dialogVisible" title="修改密码" width="500" draggable>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input v-model="form.oldPassword" autocomplete="off" type="password" show-password />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="form.newPassword" autocomplete="off" type="password" show-password />
      </el-form-item>
      <el-form-item label="重复密码" prop="repeatPassword">
        <el-input v-model="form.repeatPassword" autocomplete="off" type="password" show-password />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClickBtnCancel">取消</el-button>
        <el-button type="primary" @click="handleClickBtnSubmit">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { FormInstance } from 'element-plus'
import { useUsersStore } from '../../stores'
import http from '../../http'
import ResultMessage from '../../utils/ResultMessage.ts'

const formRef = ref<FormInstance>()
const dialogVisible = ref(false)
const usersStore = useUsersStore().getAllState() as any
const form = reactive({
  oldPassword: '',
  newPassword: '',
  repeatPassword: '',
})
const validateRepeatPassword = (rule: any, value: string, callback: any) => {
  if (rule) {
  }
  if (value === '') {
    callback(new Error('请输入重复密码'))
  } else if (value !== form.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}
const validateOldPassword = (rule: any, value: string, callback: any) => {
  if (rule) {
  }
  if (value === '') {
    callback(new Error('请输入旧密码'))
  } else if (form.oldPassword !== usersStore.password) {
    callback(new Error('旧密码错误'))
  } else {
    callback()
  }
}
const rules = reactive({
  oldPassword: [{ required: true, validator: validateOldPassword, trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
  ],
  repeatPassword: [
    { required: true, message: '请输入重复密码', trigger: 'blur' },
    { validator: validateRepeatPassword, trigger: 'blur' },
  ],
})

const openDialog = () => {
  dialogVisible.value = true
  console.log(usersStore)
}

const formReset = () => {
  form.oldPassword = ''
  form.newPassword = ''
  form.repeatPassword = ''
}

const handleClickBtnCancel = () => {
  formReset()
  dialogVisible.value = false
  if (!formRef.value) return
  formRef.value.resetFields()
}

/**
 * 点击按钮提交表单
 */
const handleClickBtnSubmit = () => {
  // 调用表单验证方法
  formRef.value?.validate(async (valid) => {
    // 如果验证通过
    if (valid) {
      // 发起HTTP请求，修改密码
      const res = await http({
        method: 'PUT',
        path: '/dev-api/system/user/profile',
        params: {
          oldPassword: form.oldPassword,
          newPassword: form.newPassword
        },
      })
      // 根据返回结果显示消息
      ResultMessage(res.code, '修改密码')
      // 如果返回码为200，表示修改成功
      if (res.code === 200) {
        // 更新用户密码
        usersStore.password = form.newPassword
        // 更新全局用户状态
        useUsersStore().setAllState({ ...usersStore })
      }
      // 关闭对话框
      dialogVisible.value = false
    }
  })
}

defineExpose({
  openDialog,
})
</script>
